
package com.yuan.servlet;

import com.yuan.hibernate.HibernateSessionFactory;

import org.hibernate.Transaction;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HttpServlet基类 对HttpServlet进行封装
 * 
 * @author YUAN
 */
public class BaseHttpServlet extends HttpServlet {
    protected Transaction mTransaction = null;
    protected PrintWriter mPrintWriter = null;
    private static String TAG = null;
    protected String mResponse = null;

    /**
     * 销毁方法 这个方法在关闭tomcat时执行
     */
    @Override
    public void destroy() {
        super.destroy();
        closeAndClear();
    }

    /**
     * doGet()基类方法
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        TAG = this.getClass().getName();
        mResponse = null;
        System.out.println("正在运行:" + TAG);
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        mTransaction = HibernateSessionFactory.getSession().beginTransaction();
        mPrintWriter = response.getWriter();
    }

    /**
     * 关闭和清空一些缓存 hibernate的已经缓存 会影响到程序的运行 特别注意
     */
    protected synchronized void closeAndClear() {
        // TODO Auto-generated method stub
        mPrintWriter.print(mResponse);
        System.out.println("返回内容  = " + mResponse);
        org.hibernate.Session mSession = HibernateSessionFactory.getSession();
        if (mPrintWriter != null) {
            mPrintWriter.flush();
            mPrintWriter.close();
            mPrintWriter = null;
        }
        if (mTransaction != null && mTransaction.isActive())
        {
            mTransaction.commit();
            mTransaction = null;
        }
        if (mSession != null && mSession.isOpen())
        {
            mSession.flush();
            mSession.clear();
            mSession.close();
            mSession = null;
        }
        System.out.println("结束运行:" + TAG);
        System.out.println();
        mResponse = null;
        System.gc();
    }

    /**
     * doPost()基类方法
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    /**
     * init() 运行程序时执行
     */
    @Override
    public void init() throws ServletException {
        super.init();
    }
}
